package org.jdcneter;

import java.io.File;
import java.net.URLDecoder;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdcneter.system.Server;
import org.jdcneter.system.ServerConfig;
import org.jdcneter.system.ServerLoader;
/**
 * @author miao
 * @since 2008-11-15
 *
 */
public class JDSMain {
	private static Log log = LogFactory.getLog(JDSMain.class);
	private Properties props = new Properties(System.getProperties());
	
	private Server server;
	
	public JDSMain(){
		super();
	}
	
	public void boot(final String[] args) throws Exception{
		System.out.println("fsdffaf");
		log.info("server boot...");
		String homeDir = props.getProperty(ServerConfig.HOME_DIR);
		if(homeDir == null){
			String path = JDSMain.class.getProtectionDomain().getCodeSource().getLocation().getFile();
			path = URLDecoder.decode(path,"uft-8");
			File runJar = new File(path);
			File homeFile = runJar.getParentFile();
			homeDir = homeFile.getCanonicalPath();
			props.put(ServerConfig.HOME_DIR, homeDir);
		}
		String homeUrl = props.getProperty(ServerConfig.HOME_URL);
		if(homeUrl == null){
			File file = new File(homeDir);
			homeUrl = file.toURI().toURL().toString();
			props.put(ServerConfig.HOME_URL, homeUrl);
		}
		
		ServerLoader loader = new ServerLoader(props);
		
		ClassLoader parentCL = Thread.currentThread().getContextClassLoader();
		
		server = loader.load(parentCL);
		
		server.init(props);
		
		server.start();
		log.info("server started");
	}
	
	public static void main(final String[] args) throws Exception{
		System.out.println("sss");
		Runnable worker = new Runnable(){
			public void run(){
				JDSMain main = new JDSMain();
				try {
					System.out.println("dd");
					main.boot(args);
				} catch (Exception e) {
					System.err.println("Failed to boot JDStream ");
					e.printStackTrace();
				}
			}
		};
		new Thread(worker).start();
	}

}

